package com.viewsky.base.back.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import com.viewsky.base.back.bean.LoginUser;
import com.viewsky.base.back.bean.Result;
import com.viewsky.base.back.config.ServerPropertyConfig;
import com.viewsky.base.back.util.Constant;
import com.viewsky.base.back.util.JwtUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;

public class LoginInterceptor implements HandlerInterceptor
{
	@Value("${config.authentication.method}")
	private String strAuthenticationMethod;
	
	@Autowired
	private ServerPropertyConfig serverPropertyConfig;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{				
		if(Constant.AuthenticationMethod.SESSION.equals(strAuthenticationMethod))
		{
			HttpSession session = request.getSession();
			LoginUser loginUser = (LoginUser)session.getAttribute("loginUser");
			
			if(loginUser == null)
			{		
				prevent(Constant.ResultCode.NOT_LOGIN, 
						"还未登录，请先登录", response);
				
				return false;			
			}
		}
		else if(Constant.AuthenticationMethod.TOKEN.equals(strAuthenticationMethod))
		{
			String strToken = request.getHeader("Authorization");
			
			if(strToken == null)
			{
				prevent(Constant.ResultCode.NOT_LOGIN, 
						"还未登录，请先登录", response);
				
				return false;	
			}
			
			try
			{
				strToken = strToken.split("^" + Constant.DEF_TOKEN_HEADER)[1];
				
				Claims mapClaim = JwtUtil.decodeToken(strToken);
				
				String strUserId = (String)mapClaim.get("userId");
				
				if(strUserId == null)
				{		
					prevent(Constant.ResultCode.NOT_LOGIN, 
							"还未登录，请先登录", response);
					
					return false;			
				}
			}
			catch(ExpiredJwtException e)
			{
				prevent(Constant.ResultCode.TOKEN_EXPIRED, 
						"登录超时，请重新登录", response);		
				
				return false;
			}
			catch(SignatureException e)
			{
				prevent(Constant.ResultCode.TOKEN_MODIFIED, 
						"认证被篡改，请重新登录", response);	
				
				return false;
			}
			catch(Exception e)
			{
				prevent(Constant.ResultCode.INNER_ERROR, 
						e.toString(), response);
				
				return false;
			}
		}
		else 
		{
			prevent(Constant.ResultCode.INNER_ERROR, 
					"配置的config.authentication.method不合法", response);
			
			return false;
		}
		
		return true;
	}
	
	private void prevent(String strResultCode, String strMessage,
			HttpServletResponse response) throws Exception
	{
		Result result = new Result();
		
		//UTF-8编码
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
    PrintWriter pw = response.getWriter();
    
    result.setServer(serverPropertyConfig.getServer());
		result.setCode(strResultCode);
		result.setData(strMessage);
		
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		
		pw.print(result);
	}
}
